package com.yunduansing.core.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.yunduansing.core.utils.CommonUtil;
import com.yunduansing.core.utils.ResultUtil;

@Controller
@RequestMapping("/manager/upload")
public class UploadController {
	@RequestMapping(value="/uploadImg",method=RequestMethod.POST,produces="application/json;charset=utf-8")
	public String uploadImg(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest req){
		try {
			String dirName=File.separator+"upload"+File.separator+"img"+File.separator;
			File dir=new File(req.getSession().getServletContext().getRealPath(dirName));
			System.out.println(req.getSession().getServletContext().getRealPath(dirName));
			if(!dir.exists()){
				System.out.println(dir.mkdir());
			}
			String originFileName=file.getOriginalFilename();
			String filename=UUID.randomUUID().toString()+originFileName.substring(originFileName.indexOf("."));
			String path=req.getServletContext().getRealPath(dirName);
			InputStream is=file.getInputStream();
			File f=new File(path,filename);
			if(!f.exists())
				f.createNewFile();
			OutputStream os=new FileOutputStream(f);
			int length=0;  
	        byte [] buffer=new byte[1024];
	        while((length=is.read(buffer))!=-1){
	        	os.write(buffer, 0, length);
	        }
	        is.close();
	        os.close();
	        return CommonUtil.toJsonWithGson(ResultUtil.init(true,dirName+filename));
		} catch (IOException e) {
			e.printStackTrace();
			return CommonUtil.toJsonWithGson(ResultUtil.init(e));
		}
	}
}
